<template>
  <v-alert
    class="notification-warp caption"
    :style="positionStyle"
    :value="visible"
    :type="type"
    transition="scale-transition"
    dense
  >
    {{ message }}
  </v-alert>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import { BtnCallback, Message } from "../../types";

@Component
export default class VuetifyMessage extends Vue implements Message {
  id = "";

  verticalOffset = 0;

  timer = -1;

  duration = 3500;

  visible = true;

  OnClose: BtnCallback | null = null;

  message = "";

  type = "info";

  get positionStyle() {
    return {
      top: `${this.verticalOffset}px`,
    };
  }

  @Watch("visible", { immediate: true, deep: true }) onVisibleChanged() {
    if (this.visible) return;
    this.$el.addEventListener("transitionend", this.RemoveElement);
  }

  mounted(): void {
    this.startTimer();
  }

  startTimer(): void {
    if (this.duration <= 0) return;
    this.timer = window.setTimeout(() => this.onTimeout(), this.duration);
  }

  private onTimeout() {
    if (!this.visible) return;
    this.Close();
  }

  Close() {
    this.visible = false;
    this.clearTimer();
    if (this.OnClose) {
      this.OnClose();
    }
  }

  RemoveElement(): void {
    this.$el.removeEventListener("transitionend", this.RemoveElement);
    this.$destroy();
    this.$el?.parentNode?.removeChild(this.$el);
  }

  private clearTimer() {
    clearTimeout(this.timer);
  }
}
</script>

<style lang="css" scoped>
.notification-warp {
  position: fixed;
  min-width: 360px;
  left: 50%;
  transform: translateX(-50%);
}
</style>
